﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Json;
using System.Text.Json;

namespace WebApiResource.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        /// <summary>
        /// 测试
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet("Test")]
        public IActionResult GetTest()
        {
            return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
        }

        /// <summary>
        /// 获取时间不需认证
        /// </summary>
        /// <returns></returns>
        [HttpGet("NoAuthorizeDateTime")]
        public async Task<string> GetNoAuthorizeDateTime()
        {
            var strRes = $"{DateTime.Now.ToString()}....port:5002...NoAuthorize";
            return await Task.FromResult(strRes);
        }

        /// <summary>
        /// 获取时间需认证权限
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet("ServiceDateTime")]
        public async Task<string> GetServiceDateTime()
        {
            var strRes = $"授权信息:{DateTime.Now.ToString()}....port:5002...Authorize";
            return await Task.FromResult(strRes);
        }

        /// <summary>
        /// 策略授权:角色为admin
        /// </summary>
        /// <returns></returns>
        [Authorize("AdminPolicy")]
        [HttpGet("GetAdminAuthTest")]
        public IActionResult GetAdminAuthTest()
        {
            return Ok("只允许角色为admin的访问");
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet("UserInfo")]
        public async Task<string> GetUserInfo()
        {
            var res = from c in User.Claims select new { c.Type, c.Value };
            return await Task.FromResult(JsonSerializer.Serialize(res));
        }

    }
}
